﻿using MicroDBHelper;
using Microsoft.AspNetCore.Cors;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebGrease;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    [JwtAuthentication]
    [EnableCors("*")]
    public class ProductAssociationDateController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 成品关联模组生产日期 数据新增 接口
        /// </summary>
        /// <param name="PAD"></param>
        /// <returns></returns>
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] ProductAssociationDate PAD)
        {
            ReturnObject RO = new ReturnObject();
            if (PAD == null ||
                string.IsNullOrEmpty(PAD.PAD_LineBody) ||
                string.IsNullOrEmpty(PAD.PAD_ProductInformation) ||
                string.IsNullOrEmpty(PAD.PAD_ModuleProductionDatePhotoScan))
            {
                Logger.Warn("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = PAD;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var query = @"INSERT INTO ProductAssociationDate 
                                    (PADDate, PADLineBody, PADProductInformation, PADModuleProductionDatePhotoScan,PADCreateCreator,PADCreateTime)
                                    VALUES 
                                    (@Date, @LineBody, @ProductInformation, @ModuleProductionDatePhotoScan,@CreateCreator,@CreateTime);
                                    SELECT CAST(scope_identity() AS int);";

                        SqlParameter[] parameters = {
                            new SqlParameter("@Date", SqlDbType.DateTime) { Value = PAD.PAD_Date },
                            new SqlParameter("@LineBody", SqlDbType.NVarChar, 50) { Value = PAD.PAD_LineBody },
                            new SqlParameter("@ProductInformation", SqlDbType.NVarChar, 500) { Value = PAD.PAD_ProductInformation },
                            new SqlParameter("@ModuleProductionDatePhotoScan", SqlDbType.NVarChar, 1000) { Value = PAD.PAD_ModuleProductionDatePhotoScan },
                             new SqlParameter("@CreateCreator", SqlDbType.NVarChar, 50) { Value = PAD.PAD_CreateCreator },
                             new SqlParameter("@CreateTime", SqlDbType.DateTime) { Value = DateTime.Now }
                        };

                        using (var command = new SqlCommand(query, connection, transaction))
                        {
                            command.Parameters.AddRange(parameters);
                            var result = await command.ExecuteScalarAsync();
                            if (result != null)
                            {
                                PAD.PAD_ID = Convert.ToInt32(result);
                                transaction.Commit();
                                Logger.Info("新增成功");
                                RO.Status = HttpStatusCode.OK;
                                RO.Message = "OK";
                                RO.Data = PAD;

                                return Request.CreateResponse(HttpStatusCode.OK, RO);
                            }
                            else
                            {
                                transaction.Rollback();
                                Logger.Error("新增失败");
                                RO.Status = HttpStatusCode.InternalServerError;
                                RO.Message = "Error";
                                RO.Data = PAD;
                                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Logger.Warn("新增失败: " + ex.Message);
                        RO.Status = HttpStatusCode.InternalServerError;
                        RO.Message = "Error" + ex.Message;
                        RO.Data = PAD;
                        return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                    }
                }
            }
        }
    }
}